$(function() {
	
	//区域联动
	$.ajax({
		url : ctx + '/manag/area/findArea', //省
		data : {type:2},
		dataType : 'json',
		type : 'post',
		success : function(json){
			
			var data = json.data;
			
			if(json.status == "success"){
				
				var selected = $('#s_province').data('selected');
				
				$('#s_province').html('<option value="0">请选择</option>');
				
				for(var i=0; i<data.length; i++){
					
					if(selected != null &&　selected == data[i].id){
						$('#s_province').append('<option selected="selected" value="'+data[i].id+'">'+data[i].name+'</option>');
						$('#s_province').change();
					}else{
						$('#s_province').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
					}
				}
			}
		},
		error : function(){
			toastr.error('系统错误');
		}
		
	});
	
	
	$('#s_province').change(function(){
		
		var parentId = $(this).val();
		
		$.ajax({
			url : ctx + '/manag/area/findArea', //市
			data : {type:3,parentId:parentId},
			dataType : 'json',
			type : 'post',
			success : function(json){
				
				var data = json.data
				
				if(json.status == "success"){
					
					var selected = $('#s_city').data('selected');
					
					$('#s_city').html('<option value="0">请选择</option>');
					
					for(var i=0; i<data.length; i++){
						if(selected != null &&　selected == data[i].id){
							$('#s_city').append('<option selected="selected" value="'+data[i].id+'">'+data[i].name+'</option>');
						}else{
							$('#s_city').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
						}
					}
					$('#s_city').change();
				}
			},
			error : function(){
				toastr.error('系统错误');
			}
			
		});
	})
	
	$('#s_city').change(function(){
		
		var parentId = $(this).val();
		
		$.ajax({
			url : ctx + '/manag/area/findArea', //区县
			data : {type:4,parentId:parentId},
			dataType : 'json',
			type : 'post',
			success : function(json){
				
				var data = json.data;
				
				if(json.status == "success"){
					
					var selected = $('#s_county').data('selected');
					
					$('#s_county').html('<option value="0">请选择</option>');
					
					for(var i=0; i<data.length; i++){
						if(selected != null &&　selected == data[i].id)
							$('#s_county').append('<option selected="selected" value="'+data[i].id+'">'+data[i].name+'</option>');
						else
							$('#s_county').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
					}
				}
			},
			error : function(){
				toastr.error('系统错误');
			}
			
		});
	})
	
	
	//图片上传无限添加
	$(document).on('change', 'input.dropify', function() {			
		
		var inputName = $(this).attr('extra');			
		
		var str = '<div class="box pull-left mr"> <input type="file" extra="'+inputName+'" class="dropify" data-default-file="" accept=".gif,.jpg,.jpeg,.png"> </div>';
		
		var count = 0;
	 
		$('input.dropify[extra="'+inputName+'"]').each(function(){
			
			if($(this).parent('div').hasClass('has-preview')){
			
				count++ ;
			}
		
		})
		
		console.log(count);
		
		if(count>=4 && count<7 && $('input.dropify[extra="'+inputName+'"]').size()<8){
		
			$(this).parent().parent().parent().append(str).bind('click', function() {
			  $('.dropify').dropify({
				  messages: {
					  'default': '点击或拖拽文件到这里',
					  'replace': '点击或拖拽文件到这里来替换文件',
					  'remove':  '移除文件',
					  'error':   '对不起，你上传的文件太大了'
				  }
			  });
		    })
		  
		    $('.dropify').dropify({
					messages: {
					'default': '点击或拖拽文件到这里',
					'replace': '点击或拖拽文件到这里来替换文件',
					'remove':  '移除文件',
					'error':   '对不起，你上传的文件太大了'
		       }
			});
			
			var oValue = $('input[name="'+inputName+'"]').val();
			
			$('input[name="'+inputName+'"]').val(oValue + ",null");
		
		}
		
		uploadFile(this);
					
	});
	
	
	
	
	$(".radio_btn").click(function(){
		if($(this).find(".checkbox-slider").is(':checked')){
			$(".server_2").hide();
			$(".server_1").stop().slideToggle(500);
		}else {
			$(".server_1").hide();
			$(".server_2").stop().slideToggle(500);
		}
	});

   $('.dropify').dropify({
	 messages: {
		 'default': '点击或拖拽文件到这里',
		 'replace': '点击或拖拽文件到这里来替换文件',
		 'remove':  '移除文件',
		 'error':   '对不起，你上传的文件太大了'
	 }
   });
	
   //form验证
	$("#registrationForm").bootstrapValidator();
	$("#registrationForm").on('success.form.bv', function(e) {
        e.preventDefault();
    });
	
	var from = $('#from').val();
	
	$('input[name="name"]').removeAttr('readonly');
	
	if(from == "check"){
		$('#registrationForm').find('input').attr('disabled', 'disabled');
		$('#registrationForm').find('select').attr('disabled', 'disabled');
		$('#registrationForm').find('textarea').attr('disabled', 'disabled');
		$('#registrationForm').find('button').attr('disabled', 'disabled');
	}
	
	if(from == "approval"){
		$('#registrationForm').find('input').attr('disabled', 'disabled');
		$('#registrationForm').find('select').attr('disabled', 'disabled');
		$('#registrationForm').find('textarea').attr('disabled', 'disabled');
		$('#registrationForm').find('button').attr('disabled', 'disabled');
		
		//审核状态下，显示审核单选项
		$('#applyStatus').show();
		$('input[name="id"]').removeAttr('disabled');
		$('input[name="name"]').removeAttr('disabled');
		$('input[name="status"]').removeAttr('disabled');
		$('textarea[name="reason"]').removeAttr('disabled');
		$('#submitInput').removeAttr('disabled');
		
	}
	
	//时间控件
	$("body").on("focus.page", ".date-picker", function() {
		$(this).datetimepicker({
			format : "yyyy-mm-dd",
			minView : 2,
			autoclose : true,
			language : "zh-CN"
		})
	});
	
    $("#test-upload").fileinput({
        'showPreview' : false,
        'allowedFileExtensions' : ['jpg', 'png','gif'],
        'elErrorContainer': '#errorBlock'
    });
	
    
    $('input[name="isOneCheck"]').change(function(){
    	if($(this).is(':checked')){
    		$(this).val(1);
    		$('input[name="isOne"]').val(1);
    	}else{
    		$(this).val(0);
    		$('input[name="isOne"]').val(0);
    	}
    });
    
    
});




//文件上传
function uploadFile(t){
	
	var _this = $(t);
	
    var formData = new FormData();  
    
    formData.append('uploadfile', _this[0].files[0]);
    
    var inputName = _this.attr('extra');
    	
    $.ajax({  
        url: ctx + '/pic/uploadFile' ,  
        type: 'POST',  
        data: formData,  
        async: false,  
        cache: false,  
        contentType: false,  
        processData: false,
        success: function (data) { 
        	
        	if(data.status == "success"){
        		
        		var oValue = $('input[name="'+inputName+'"]').val();
        		
        		if(oValue.length == 0){
        			oValue = "null,null,null,null,null";
        		}
        		
        		var nValue = "";
        		
        		var index = _this.index('input[extra="'+inputName+'"]');//当前编辑的图片下标
        		var oValueArray = oValue.split(',');//已添加图片
        		
        		//console.log(index);
        		//console.log(oValueArray);
        		//console.log(oValueArray.length);
        		
        		//已经编辑过的图片
        		if(index < oValueArray.length){
        			oValueArray[index] = data.path;
        			
        			for(var i=0; i<oValueArray.length; i++){
        				if(i == oValueArray.length-1)
        					nValue  = nValue + oValueArray[i];
        				else
        					nValue  = nValue + oValueArray[i] + ",";
        			}
        			
        			$('input[name="'+inputName+'"]').val(nValue);
        			
        			//console.log($('input[name="'+inputName+'"]').val());
        			
        		}else{
        			if(oValue != null && oValue != "")
        				nValue = oValue + "," + data.path;
            		else
            			nValue = data.path;
            			
            		$('input[name="'+inputName+'"]').val(nValue);
            		
            		//console.log($('input[name="'+inputName+'"]').val());
        		}
        		
        		//console.log(nValue		);
        		
        	}else{	
        		toastr.error('上传失败！');
        	}
        	
        },
        error: function(){
        	toastr.error('系统错误');
        }
	});
};








function validateForm(form, callback, confirmMsg){
	
	
	 var $form = $(form);

     var formData = $form.data('bootstrapValidator');
     if (formData) {
    	 // 修复记忆的组件不验证
    	 formData.validate();

		if (!formData.isValid()) {
			return false;
		}
    }
     
    // console.log($('#registrationForm').serialize());
     
     
	
	$.ajax({
		url : ctx + '/franchisee/addFranchisee',
		data : $('#registrationForm').serialize(),
		dataType : 'json',
		type : 'post',
		success : function(data){
			if(data.status != "success"){
				toastr.error(data.msg);
			}else{
				location.href = ctx + '/franchisee/franchisee';
			}
		},
		error : function(){
			toastr.error("系统错误");
		}
	});
	
	return false;
}




$("#file-1").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-2").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-3").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-4").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-5").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-6").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-7").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});
 $("#file-8").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});

 $("#file-9").fileinput({
    uploadUrl: '#', 
    allowedFileExtensions : ['jpg', 'png','gif'],
    overwriteInitial: false,
    maxFileSize: 100,
    maxFilesNum: 10,
   
    slugCallback: function(filename) {
        return filename.replace('(', '_').replace(']', '_');
    }
});


 $(".check-status").find("span").click(function(){
     if($(".check-status").find("span").index(this) == 0){
         $(this).prev().attr("checked","checked");
         $("#applyReason").hide()
     }else {
         $(this).prev().removeAttr("checked");
         $("#applyReason").show()
     }
 })













